package com.caiheng.api.commons.config;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @创建者：zhouwei
 * @创建时间：2022/8/9
 * @描述：
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private final Logger log = LoggerFactory.getLogger(getClass());
    private static String key = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
    private static Set<String> notAllowedKeyWords = new HashSet<>(0);
    private static String replacedString="INVALID";
    private Map<String, String[]> parameterMap;
    private final byte[] body;

    static {
        String keyStr[] = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }

    private String currentUrl;

    public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) throws IOException{
        super(servletRequest);
        parameterMap = servletRequest.getParameterMap();
        currentUrl = servletRequest.getRequestURI();
        body = StreamUtils.copyToByteArray(servletRequest.getInputStream());
        String result = new String(body,"UTF-8");
        System.out.println("result: " + result);
        cleanXSS(result);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {            }
        };
    }

    /**覆盖getParameter方法，将参数名和参数值都做xss过滤。
     * 如果需要获得原始的值，则通过super.getParameterValues(name)来获取
     * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
     */
    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }
    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }
    @Override
    public Map<String, String[]> getParameterMap(){
        Map<String, String[]> values = super.getParameterMap();
        if (values == null) {
            return null;
        }
        Map<String, String[]> result = new HashMap<>();
        for(String key:values.keySet()){
            String encodedKey = cleanXSS(key);
            int count = values.get(key).length;
            String[] encodedValues = new String[count];
            for (int i = 0; i < count; i++){
                encodedValues[i] = cleanXSS(values.get(key)[i]);
            }
            result.put(encodedKey,encodedValues);
        }
        return result;
    }
    /**
     * 覆盖getHeader方法，将参数名和参数值都做xss过滤。
     * 如果需要获得原始的值，则通过super.getHeaders(name)来获取
     * getHeaderNames 也可能需要覆盖
     */
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }

    private String cleanXSS(String valueP) {
        System.out.println("处理前数据： " + valueP);
        // You'll need to remove the spaces from the html entities below
        String value = valueP.replaceAll("<", "&lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", " ");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        value = value.replaceAll("[*]","["+"*]");
        value = value.replaceAll("[+]","["+"+]");
        value = value.replaceAll("[?]","["+"?]");

        value = cleanSqlKeyWords(value);
        // replace sql 这里可以自由发挥
//        String[] values = value.split(" ");
//
//        String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|%|chr|mid|master|truncate|" +
//                "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +
//                "table|from|grant|use|group_concat|column_name|" +
//                "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|" +
//                "chr|mid|master|truncate|char|declare|or|;|-|--|,|like|//|/|%|#";
//
//        String[] badStrs = badStr.split("\\|");
//        for (int i = 0;i<badStrs.length;i++){
//            for (int j = 0;j<values.length;j++){
//                if (values[j].equalsIgnoreCase(badStrs[i])){
//                    values[j] = "forbid";
//                }
//            }
//        }
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0;i<values.length;i++){
//            if (i == values.length-1){
//                sb.append(values[i]);
//            } else {
//                sb.append(values[i]+" ");
//            }
//        }
//
//        value = sb.toString();

        System.out.println("处理后数据： " + value);
        return value;
    }

    private String cleanSqlKeyWords(String value) {
        String paramValue = value;
        System.out.println("paramValue: " + paramValue);
        for (String keyword : notAllowedKeyWords) {
            System.out.println("keyword: " + keyword);
            System.out.println("paramValue.length(): " + paramValue.length());
            System.out.println("keyword.length() + 4: " + keyword.length() + 4);
            if (paramValue.length() > keyword.length() + 4
                    && (paramValue.contains(" " + keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" ")||paramValue.contains(keyword))) {
                paramValue = StrUtil.replace(paramValue, keyword, replacedString);
                log.error(this.currentUrl + "已被过滤，因为参数中包含不允许sql的关键词(" + keyword
                        + ")"+";参数："+value+";过滤后的参数："+paramValue);
            }
        }
        return paramValue;
    }

}
